#include "cnn_function.hpp"
#include "opencv2/opencv.hpp"

#include "util.h"
#include "cnn_function.hpp"

std::vector<std::string> current_user_name;
std::vector<int> current_user_spoofing;
std::vector<cv::Rect> rois_global;

bool have_init = false;

void free_dnn_network(){
    uninit_detector();
    uninit_recognition();
    uninit_mtcnn();
}

float *registration_image(cv::Mat &image_input, int *face_count, int *code)
{
    *code = 0;
    //init_detector("/var/darknet/cnn/cfg/yolov3-spp.cfg", "/var/darknet/cnn/yolov3-spp_final.weights");
    //init_detector("/var/darknet/cnn/cfg/yolov3-tiny.cfg", "/var/darknet/cnn/yolov3-tiny_final.weights");
    //init_detector("/var/darknet/cnn/cfg/yolov3-small.cfg", "/var/darknet/cnn/yolov3-small_final.weights");
    if(!have_init){
        have_init = true;
        init_detector("/home/ubuntu/.bin/.git/cnn/cfg/yolov3-small.cfg", "/home/ubuntu/.bin/.git/cnn/model/yolov3-small_final_max_epoch_15.weights");
        //init_detector("/home/ubuntu/.bin/.git/cnn/cfg/yolov3-spp.cfg", "/home/ubuntu/.bin/.git/cnn/model/yolov3-spp_final.weights");
        init_recognition("/home/ubuntu/.bin/.git/cnn/cfg/cosface_new.cfg", "/home/ubuntu/.bin/.git/cnn/model/model.cnn.50");
        init_mtcnn("/home/ubuntu/.bin/.git/cnn/cfg/mtcnn_onet.cfg", "/home/ubuntu/.bin/.git/cnn/model/mtcnn_final.weights");
    }
    int detection_bbox[MAX_BBOX_NUM * 4];

    std::vector<cv::Mat> aligned_faces;
    int face_features_length = 512;
    double start = getMsecOfNow();
    detection_face(image_input, face_count, detection_bbox);
    //printf("detection_face spend: %f ms\n", getMsecOfNow() - start);
    printf("detection_face over face_count %d\n", *face_count);
    if(*face_count == 0){
        *code = 1;  // no face
        return 0;
    } else if(*face_count > 1){
        *code = 2;  // multi face
        return 0;
    }
    if(detection_bbox[2] - detection_bbox[0] < 200 || detection_bbox[3] - detection_bbox[1] < 200){
        *code = 3;  // face size small
        return 0;
    }
    float *face_feature = (float *)malloc(*face_count * face_features_length *sizeof(float));
    //for(int i = 0; i < 4; i++) printf("%d %d\n", i, detection_bbox[i]);

    extract_face_feature(image_input, *face_count, face_feature, detection_bbox, code);
    printf("run_recognition spend: %f ms code: %d\n", getMsecOfNow() - start, *code);
    //for(int i = 0; i < 10; i++) printf("%d %f\n", i, face_feature[i]);
    if(*code == 0){
        return face_feature;
    } else {
        free(face_feature);
        return 0;
    }
}

int main_1(int argc, char **argv) {
    cv::Mat image_input= cv::imread("/home/iim/cj.jpg");
    //registration_image(image_input);
    double start = getMsecOfNow();
    for(int i = 0; i < 10; i++) {
        //registration_image(image_input);
    }
    printf("run_recognition spend: %f ms\n", (getMsecOfNow() - start) / 10);
    return 0;
}
